package com.ekuaitu.kuaitu.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.services.core.LatLonPoint;
import com.bumptech.glide.Glide;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.bean.ConfirmCertifyBean;
import com.ekuaitu.kuaitu.bean.ParkDetailBean;
import com.ekuaitu.kuaitu.bean.PlaceOrderBean;
import com.ekuaitu.kuaitu.bean.UnFinishOrderBean;
import com.ekuaitu.kuaitu.map.GeocodeSearchViewUtils;
import com.ekuaitu.kuaitu.utils.AccountStatus;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.IntentUtils;
import com.ekuaitu.kuaitu.utils.KuaituDialog;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.zhy.autolayout.AutoLinearLayout;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ConfirmRentCarActivity extends BaseActivity {
    @BindView(R.id.iv_confirm_rent_car)
    ImageView ivConfirmRentCar;
    @BindView(R.id.tv_confirm_rent_brand)
    TextView tvConfirmRentBrand;
    @BindView(R.id.tv_confirm_rent_plate)
    TextView tvConfirmRentPlate;
    @BindView(R.id.tv_confirm_rent_seats)
    TextView tvConfirmRentSeats;
    @BindView(R.id.tv_confirm_rent_battery)
    TextView tvConfirmRentBattery;
    @BindView(R.id.tv_confirm_rent_dayPrice)
    TextView tvConfirmRentDayPrice;
    @BindView(R.id.tv_confirm_rent_nightPrice)
    TextView tvConfirmRentNightPrice;
    @BindView(R.id.tv_confirm_rent_parkName)
    TextView tvConfirmRentParkName;
    @BindView(R.id.rb_confirm_rent_rsbz)
    ImageView toggleButtonConfirmRent;
    @BindView(R.id.tv_confirm_rent_sdew)
    TextView tvConfirmRentSdew;
    @BindView(R.id.tv_confirm_rent_passenger)
    TextView tvConfirmRentPassenger;
    @BindView(R.id.tv_confirm_rent_rsbz)
    TextView tvConfirmRentRsbz;
    @BindView(R.id.car_day_time)
    TextView carDayTime;
    @BindView(R.id.car_night_time)
    TextView carNightTime;


    @BindView(R.id.progressBar_rent)
    AutoLinearLayout progressBar_rent;

    private Context mContext = this;
    private LatLonPoint carLatLngPoint;
    private ParkDetailBean.AttachmentBean.CarsBean carsBean;
    private String carId;
    private String parkId;
    private String isCompanyByRisk = "0";
    private boolean isChecked = false;

    @Override
    public int getLayoutId() {
        return R.layout.activity_confirm_rent;
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        carsBean = (ParkDetailBean.AttachmentBean.CarsBean) bundle.getSerializable("carsBean");
        carLatLngPoint = new LatLonPoint(carsBean.getLatitude(), carsBean.getLongitude());
        GeocodeSearchViewUtils geocodeSearchViewUtils = new GeocodeSearchViewUtils();
        geocodeSearchViewUtils.startGeocodeSearch(mContext, carLatLngPoint.getLatitude(), carLatLngPoint.getLongitude(), tvConfirmRentParkName);
        tvConfirmRentBrand.setText(carsBean.getBrand() + " " + carsBean.getModel());
        tvConfirmRentPlate.setText(carsBean.getLicenseTag());
        tvConfirmRentSeats.setText(carsBean.getSeat() + "座");
        tvConfirmRentBattery.setText(carsBean.getMileage() + "公里");
        tvConfirmRentDayPrice.setText(((carsBean.getValuationRuleModel().getWeekDayPrice()) / 100.0) + "");
        tvConfirmRentNightPrice.setText(((carsBean.getValuationRuleModel().getWeekNightPrice()) / 100.0) + "");
        //保险价格
        tvConfirmRentSdew.setText("不计免赔：" + carsBean.getAbatement() + "元/单 (24小时)");
        tvConfirmRentPassenger.setText("人身保障：" + carsBean.getCompanyByRisk() + "元/单 (24小时)");
        Glide.with(mContext).load(MyApplication.getInstance().getImageUrl() + carsBean.getPicture()).into(ivConfirmRentCar);
        carDayTime.setText(SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.CAR_DAY_TIME));
        carNightTime.setText(SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.CAR_NIGHT_TIME));
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryWhite), 0, true);
    }


    @OnClick({R.id.tv_confirm_rent_hotLine, R.id.return_confirm_rent, R.id.linearLayout_confirm_rent_rules, R.id.tv_confirm_rent_confirm, R.id.rb_confirm_rent_rsbz, R.id.linearLayout_confirm_rent_insurance})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.return_confirm_rent:
                finish();
                break;
            case R.id.tv_confirm_rent_hotLine:
                final KuaituDialog kuaituDialog2 = new KuaituDialog(mContext);
                kuaituDialog2.setTitle(getString(R.string.dialogTitle));
                kuaituDialog2.setMessage("是否拨打客服电话" + MyApplication.getInstance().getHotLine());
                kuaituDialog2.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:" + MyApplication.getInstance().getHotLine()));
                        startActivity(intent);
                        kuaituDialog2.dismiss();
                    }
                });
                kuaituDialog2.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        kuaituDialog2.dismiss();
                    }
                });
                kuaituDialog2.show();
                break;
            case R.id.linearLayout_confirm_rent_rules:
                Intent intent = new Intent();
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "计价规则");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlConstant.Request.VALUE_RULES);
                startActivity(intent);
                break;
            case R.id.tv_confirm_rent_confirm:
                if (!AccountStatus.isLogin(mContext)) {
                    ToastCompat.makeText(mContext, getResources().getString(R.string.loginFirst), Toast.LENGTH_SHORT).show();
                    Intent intent1 = new Intent();
                    intent1.setClass(mContext, LoginActivity.class);
                    startActivity(intent1);
                } else {
                    carId = carsBean.getId() + "";
                    parkId = carsBean.getParkId() + "";
                    hasUnPayOrder();
                }
                break;

            case R.id.rb_confirm_rent_rsbz:
                if (!isChecked) {
                    isCompanyByRisk = "1";
                    isChecked = true;
                    tvConfirmRentRsbz.setTextColor(Color.rgb(102, 102, 102));
                    toggleButtonConfirmRent.setImageDrawable(getResources().getDrawable(R.drawable.image_checked));
                } else {
                    isChecked = false;
                    isCompanyByRisk = "0";
                    tvConfirmRentRsbz.setTextColor(Color.rgb(240, 85, 70));
                    toggleButtonConfirmRent.setImageDrawable(getResources().getDrawable(R.drawable.image_uncheck));
                }
                break;
            case R.id.linearLayout_confirm_rent_insurance:
                Intent intent2 = new Intent();
                intent2.setClass(mContext, WebViewActivity.class);
                intent2.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlConstant.Request.INSURANCE);
                intent2.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "保险");
                startActivity(intent2);
                break;
        }
    }

    //下单
    public void rentCar(String carId, final String parkId, String isCompanyByRisk) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).rentCar(MyApplication.getInstance().getRequestFieldMap(), carId, parkId, isCompanyByRisk).enqueue(new Callback<PlaceOrderBean>() {
            @Override
            public void onResponse(Call<PlaceOrderBean> call, Response<PlaceOrderBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    progressBar_rent.setVisibility(View.GONE);
                    if (response.body().getStatus() == 200) {
                        PlaceOrderBean.AttachmentBean.OrderBean result = response.body().getAttachment().getOrder();
                        String carBrand = "";
                        if (result.getCarModel().getModel() != null) {
                            carBrand = result.getCarModel().getBrand() + result.getCarModel().getModel();
                        }
                        String carPlate = result.getCarModel().getLicenseTag();
                        String carId = result.getCarId() + "";
                        String orderId = result.getId();
                        Intent intent = new Intent();
                        intent.putExtra("carBrand", carBrand);
                        intent.putExtra("carPlate", carPlate);
                        intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                        intent.putExtra("carId", carId);
                        intent.putExtra("picture", carsBean.getPicture());
                        intent.putExtra("parkId", parkId);
                        intent.putExtra("carLatitude", result.getCarModel().getLatitude() + "");
                        intent.putExtra("carLongitude", result.getCarModel().getLongitude() + "");
                        setResult(Constants.RESULT_RENT, intent);
                        finish();
                    } else if (response.body().getStatus() == 400) {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    } else if (response.body().getStatus() == 401) {
                        //这里只返回了一种不满足的资格，跳转资格认证步骤还需要获得其他资格状态，所以还需要checkUserStatus();
                        checkUserStatus(3);
                    } else if (response.body().getStatus() == 402) {
                        checkUserStatus(1);
                    } else if (response.body().getStatus() == 403) {
                        checkUserStatus(2);
                    } else if (response.body().getStatus() == 404) {
                        progressBar_rent.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, "您有未完成订单", Toast.LENGTH_LONG).show();
                        final KuaituDialog kuaituDialog = new KuaituDialog(mContext);
                        kuaituDialog.setTitle(getString(R.string.dialogTitle));
                        kuaituDialog.setMessage(getString(R.string.unPayOrder));
                        kuaituDialog.setYesOnclickListener("支付", new KuaituDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                Intent intent = new Intent(mContext, MyRouteActivity.class);
                                startActivity(intent);
                                kuaituDialog.dismiss();
                            }
                        });
                        kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                kuaituDialog.dismiss();
                            }
                        });
                        kuaituDialog.show();
                    } else if (response.body().getStatus() == 405) {
                        final KuaituDialog kuaituDialog = new KuaituDialog(mContext);
                        kuaituDialog.setTitle(getString(R.string.dialogTitle));
                        kuaituDialog.setMessage(getString(R.string.rechargeRemind));
                        kuaituDialog.setYesOnclickListener("充值", new KuaituDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                Intent intent = new Intent(mContext, ChargeMoneyActivity.class);
                                startActivity(intent);
                                kuaituDialog.dismiss();
                            }
                        });
                        kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                kuaituDialog.dismiss();
                            }
                        });
                        kuaituDialog.show();
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    //账号过期，跳转登录界面
                    progressBar_rent.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<PlaceOrderBean> call, Throwable t) {
                progressBar_rent.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    //跳转资格认证步骤需要获得其他资格状态，所以还需要checkUserStatus();
    private void checkUserStatus(final int SubmitFlag) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).confirmCertify(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<ConfirmCertifyBean>() {
            @Override
            public void onResponse(Call<ConfirmCertifyBean> call, Response<ConfirmCertifyBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    progressBar_rent.setVisibility(View.GONE);
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.IDENTITY_STATUS, response.body().getAttachment().getIdentityStatus() + "");
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.LICENSE_STATUS, response.body().getAttachment().getLicenseStatus() + "");
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.DEPOSIT_STATUS, response.body().getAttachment().getDepositStatus() + "");
                        if (SubmitFlag == 3) {
                            ToastCompat.makeText(mContext, "您还未支付保证金", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(mContext, CarCertificateActivity.class);
                            intent.putExtra("SubmitFlag", 3);
                            startActivity(intent);
                        } else if (SubmitFlag == 1) {
                            ToastCompat.makeText(mContext, "您还未实名认证和证照认证", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(mContext, CarCertificateActivity.class);
                            intent.putExtra("SubmitFlag", 1);
                            startActivity(intent);
                        } else if (SubmitFlag == 2) {
                            ToastCompat.makeText(mContext, "您还未证照认证", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(mContext, CarCertificateActivity.class);
                            intent.putExtra("SubmitFlag", 2);
                            startActivity(intent);
                        }
                    } else {
                        progressBar_rent.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<ConfirmCertifyBean> call, Throwable t) {
                progressBar_rent.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                Log.i("neterror", "008");
            }
        });
    }

    private void hasUnPayOrder() {
        progressBar_rent.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getUnFinishOrder(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<UnFinishOrderBean>() {
                    @Override
                    public void onResponse(Call<UnFinishOrderBean> call, final Response<UnFinishOrderBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                if (response.body().getAttachment().getIsUnfinished() != 0) {
                                    if (response.body().getAttachment().getBusinessType() == 1) {       //电车未完成订单
                                        progressBar_rent.setVisibility(View.GONE);
                                        switch (response.body().getAttachment().getStatus()) {
                                            case 15:
                                            case 16:
                                            case 17:
                                                final KuaituDialog kuaituDialog = new KuaituDialog(mContext);
                                                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                                                kuaituDialog.setMessage(getString(R.string.unPayOrder));
                                                kuaituDialog.setYesOnclickListener("支付", new KuaituDialog.onYesOnclickListener() {
                                                    @Override
                                                    public void onYesClick() {
                                                        IntentUtils.toSettlementActivity(mContext, response.body().getAttachment().getOrderId(), "");
                                                        kuaituDialog.dismiss();
                                                    }
                                                });
                                                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                                    @Override
                                                    public void onNoClick() {
                                                        kuaituDialog.dismiss();
                                                    }
                                                });
                                                kuaituDialog.setCancelable(false);
                                                kuaituDialog.show();
                                                break;
                                        }
                                    } else {    //单车未完成订单
                                        progressBar_rent.setVisibility(View.GONE);
                                        switch (response.body().getAttachment().getStatus()) {
                                            case 15:
                                                final KuaituDialog kuaituDialog = new KuaituDialog(mContext);
                                                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                                                kuaituDialog.setMessage(getString(R.string.unPayOrder));
                                                kuaituDialog.setYesOnclickListener("支付", new KuaituDialog.onYesOnclickListener() {
                                                    @Override
                                                    public void onYesClick() {
                                                        IntentUtils.toSettlementActivity(ConfirmRentCarActivity.this, response.body().getAttachment().getOrderId(),
                                                                response.body().getAttachment().getOrderModel().getBikeModel().getBikeId());
                                                        kuaituDialog.dismiss();
                                                    }
                                                });
                                                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                                    @Override
                                                    public void onNoClick() {
                                                        kuaituDialog.dismiss();
                                                    }
                                                });
                                                kuaituDialog.setCancelable(false);
                                                kuaituDialog.show();
                                                break;
                                        }
                                    }
                                } else {  //没有未完成订单
                                    rentCar(carId, parkId, isCompanyByRisk);
                                }
                            } else {
                                progressBar_rent.setVisibility(View.GONE);
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<UnFinishOrderBean> call, Throwable t) {
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                    }
                });
    }
}
